﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurrentBehaviorCannon : MonoBehaviour
{
    private Turrent thisTurrent;

    [SerializeField] private GameObject enemy1;

    private GameObject bulletprefab;

    private Transform muzzleTransform;
    private GameObject closest;

    [SerializeField] private float shotSpeed, shotTimer;
    // Start is called before the first frame update
    void Start()
    {
        thisTurrent = new Turrent(0);
        muzzleTransform = this.gameObject.transform.GetChild(0).GetChild(0);
        bulletprefab = Resources.Load("Prefab/Bullet") as GameObject;
    }

    // Update is called once per frame
    void Update()
    {
        enemy1 = FindClosestEnemy();
        if (enemy1 != null)
        {
            transform.LookAt(enemy1.transform,Vector3.up);
        }
        else
        {
            transform.rotation = Quaternion.Euler(transform.forward);
        }
        this.transform.localRotation = Quaternion.Euler(0,transform.localRotation.eulerAngles.y,transform.localRotation.eulerAngles.z);
        Turrentshoot();
    }

    public GameObject FindClosestEnemy()
    {
        //查找标签为Enemy的全部游戏物体
        if (GameObject.FindWithTag("Enemy") != null)
        {
            closest = GameObject.FindWithTag("Enemy");
            if (GameObject.FindGameObjectsWithTag("Enemy") != null)
            {
                GameObject[] findList;
                findList = GameObject.FindGameObjectsWithTag("Enemy");
                float distance = Mathf.Infinity;
                Vector3 position = this.transform.position;
                foreach (GameObject go in findList)
                {
                    float diff = Vector3.Distance(position, go.transform.position);
                    var curDistance = diff;
                    if (curDistance < distance)
                    {
                        closest = go; //更新最近距离敌人
                        distance = curDistance; //更新最近距离
                    }
                }
            }
            return closest;
        }
        return null;
    }

    void Turrentshoot()
    {
        if (enemy1 != null)
        {
            if (Vector3.Distance(enemy1.transform.position, this.gameObject.transform.position) <= 60) ;
            {
                shotTimer++;
                if (shotTimer >= shotSpeed)
                {
                    bulletprefab.GetComponent<Bullet>().targetObj = enemy1;
                    Instantiate(bulletprefab,muzzleTransform.position,muzzleTransform.rotation);
                    shotTimer = 0;
                }
            }
        }
    }
}
